package com.ctsi.organise.app.rest;

import com.ctsi.commons.util.StringUtil;
import com.ctsi.commons.util.UtilMisc;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.id.UUIDGenerator;
import com.ctsi.commons.util.request.UtilHttp;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.common.response.UnifiedResponse;
import com.ctsi.framework.security.util.SecurityUtil;
import com.ctsi.organise.common.constant.PartyType;
import com.ctsi.organise.common.model.Organise;
import com.ctsi.organise.dto.SupportUserDTO;
import com.ctsi.organise.entity.OrganiseEntity;
import com.ctsi.organise.entity.PersonEntity;
import com.ctsi.organise.entity.UserExpertEntity;
import com.ctsi.organise.service.OrganiseEntityManager;
import com.ctsi.organise.service.PersonEntityManager;
import com.ctsi.organise.service.UserExpertEntityService;
import com.ctsi.system.service.api.DictionayTreeServiceProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author: zhangjw
 * @Date: 2018/11/2 01:46
 * @Description:
 */
@RestController
public class UserExpertController {

    @Autowired
    private UserExpertEntityService userExpertEntityService;
    @Autowired
    private OrganiseEntityManager organiseEntityService;
    @Autowired
    private PersonEntityManager userEntityService;
    @Autowired
    private DictionayTreeServiceProxy dictionayTreeServiceProxy;

    /**
     * 查看标签
     * @param pageQueryRequest
     * @return
     */
    @PostMapping(value = "/expets/tags")
    public UnifiedResponse<Page<ExpertPageQueryResponse>> page(@RequestBody ExpertPageQueryRequest pageQueryRequest){
        Map<String,Object> params = UtilHttp.filterBlank(UtilMisc.toMap(pageQueryRequest));
       Page<UserExpertEntity> experts = userExpertEntityService.findByMulitCondition(params,pageQueryRequest.getStart(),pageQueryRequest.getPageSize());
       List<ExpertPageQueryResponse> result =experts.getResult().stream().map(expert -> {
                   ExpertPageQueryResponse response = new ExpertPageQueryResponse();
                   response.setExpertTag(expert.getExpertTag());
                   response.setId(expert.getId());
                   response.setIsC(expert.getIsC());
                   response.setIsD(expert.getIsD());
                   response.setOrganId(expert.getOrganId());
                   response.setDepartId(expert.getDepartId());
                   response.setUserId(expert.getUserId());
                   List<OrganiseEntity> exs = organiseEntityService.getOrganiseChain(expert.getDepartId());
                   List<String> organNames = exs.stream().map(ex -> UtilValidate.isNotEmpty(ex.getShortName())? ex.getShortName() : ex.getOrganiseName()).collect(Collectors.toList());
                   response.setOrganChainName(StringUtil.join(organNames,"/"));
                   List<String> tags = dictionayTreeServiceProxy.getTreeDataNameChain("support-type",expert.getExpertTag());
                   response.setExpertTagName(StringUtil.join(tags,"/"));
                   PersonEntity user = userEntityService.findPersonEntityById(expert.getUserId());
                   response.setUserName(user.getFullName());
                   return response;
               }).collect(Collectors.toList());
        return UnifiedResponse.ok(UtilValidate.isEmpty(result) ? new Page<>() : new Page<>(pageQueryRequest.getStart(), experts.getTotalCount(), experts.getPageSize(), result));
    }

    @PostMapping(value = "/experts/add")
    public UnifiedResponse<Void> addUserExpert (@RequestBody UserExpertAddRequest addRequest) {

        //检查专家库
        String tags = addRequest.getExpertTag();
        String[] tagss = tags.split(",");
        //set去重
        Set<String> ta = new HashSet<>(Arrays.asList(tagss));

      List<UserExpertEntity> users = ta.stream().map(tag -> {
            UserExpertEntity entity = new UserExpertEntity();
            entity.setId(UUIDGenerator.getId());
            entity.setUserId(addRequest.getUserId());
            entity.setExpertTag(tag);
            entity.setIsC(0);
            entity.setIsD(0);
            entity.setStructId(entity.getId());
            List<Organise> depart = userEntityService.getBelongOrgan(addRequest.getUserId());
            if (UtilValidate.isNotEmpty(depart)){
                entity.setDepartId(depart.get(0).getPartyId());
                OrganiseEntity organ = organiseEntityService.findParentOrganWithPartyType(depart.get(0).getPartyId(), PartyType.MINORGAN);
                if (organ == null) {
                    entity.setDepartId(depart.get(0).getPartyId());
                } else {
                    entity.setOrganId(organ.getPartyId());
                }
            }
            return entity;
        }).collect(Collectors.toList());


        userExpertEntityService.insertUserExperList(users);
        return UnifiedResponse.ok();
    }
    @DeleteMapping(value = "/experts/{userId}")
    public UnifiedResponse<Void> delete(@PathVariable("userId") String userId){
        userExpertEntityService.deleteByUserId(userId);
        return UnifiedResponse.ok();
    }


    @PostMapping(value = "/experts/delete")
    public UnifiedResponse<String> deleteTag(@RequestParam("id") String id){
        String[] ids = id.split(",");
        int result = Stream.of(ids).mapToInt(_id ->
            userExpertEntityService.removeUserExpertEntity(_id)
        ).sum();
        return UnifiedResponse.ok("选中"+ids.length+"条数据,成功删除"+result+"条!");
    }
    /**
     * 人员
     */
    @PostMapping(value = "/expets/page")
    public UnifiedResponse<Page<ExpertPageQueryResponse>> pageUser(@RequestBody ExpertPageQueryRequest pageQueryRequest){
        Map<String,Object> params = UtilHttp.filterBlank(UtilMisc.toMap(pageQueryRequest));
        Page<UserExpertEntity> experts = userExpertEntityService.findUser(params,pageQueryRequest.getStart(),pageQueryRequest.getPageSize());
        List<ExpertPageQueryResponse> result =experts.getResult().stream().map(expert -> {
            ExpertPageQueryResponse response = new ExpertPageQueryResponse();
            response.setExpertTag(expert.getExpertTag());
            response.setId(expert.getId());
            response.setIsC(expert.getIsC());
            response.setIsD(expert.getIsD());
            response.setOrganId(expert.getOrganId());
            response.setDepartId(expert.getDepartId());
            response.setUserId(expert.getUserId());
            List<OrganiseEntity> exs = organiseEntityService.getOrganiseChain(expert.getDepartId());
            List<String> organNames = exs.stream().map(ex -> UtilValidate.isNotEmpty(ex.getShortName())? ex.getShortName() : ex.getOrganiseName()).collect(Collectors.toList());
            response.setOrganChainName(StringUtil.join(organNames,"/"));
            List<String> tags = dictionayTreeServiceProxy.getTreeDataNameChain("support-type",expert.getExpertTag());
            response.setExpertTagName(StringUtil.join(tags,"/"));
            PersonEntity user = userEntityService.findPersonEntityById(expert.getUserId());
            response.setUserName(user.getFullName());
            return response;
        }).collect(Collectors.toList());
        return UnifiedResponse.ok(UtilValidate.isEmpty(result) ? new Page<>() : new Page<>(pageQueryRequest.getStart(), experts.getTotalCount(), experts.getPageSize(), result));
    }

    /**
     * 打标签时的支撑人员列表
     * @param personName
     * @param start
     * @param pageSize
     * @return
     */
    @PostMapping(value = "/experts/supports")
    public UnifiedResponse<Page<SupportUserDTO>> supportList(@RequestParam(value = "personName",required = false) String personName,
                                                             @RequestParam(value = "supportTags",required = false) String supportTags,
                                                             @RequestParam(value = "start") int start,
                                                             @RequestParam(value = "pageSize",required = false,defaultValue = Page.DEFAULT_PAGESIZE) int pageSize){
        Map<String,Object> params = new HashMap<>();
        if (UtilValidate.isNotEmpty(personName)) {
            params.put("personName","%"+personName+"%");
        }
        if (UtilValidate.isNotEmpty(supportTags)) {
            String[] tags = supportTags.split(",");
            params.put("supportTags",tags);
        }
        Page<SupportUserDTO> page = userExpertEntityService.findSupportRoleUser(params, SecurityUtil.getUser().getLoginId(),start, pageSize);
        page.getResult().forEach(dto ->{
            String departId = dto.getOrganName();
           String chainName = organiseEntityService.getOrganiseChain(departId).stream().map(org -> org.getOrganiseName()).collect(Collectors.joining("/"));
           dto.setOrganName(chainName);
        });
        return UnifiedResponse.ok(page);
    }

}
